package view.order;

import connectivity.QueryManager;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import main.WinkelApplication;
import model.OrderRule;
import model.Product;

/**
 *
 * @author Dennis Nijssen
 */
public class OrderEditFrame extends JFrame
{    
    private JTable orderRuleTable;
    private DefaultTableModel model;
    
    private JTextField txtProductId;
    private JTextField txtNaam;
    private JTextField txtAmount;
    private JTextField txtPrice;
    
    private final int orderId;
    
    public OrderEditFrame(int orderId)
    {
        super();
        
        this.model = new DefaultTableModel();
        this.orderId = orderId;
        
        getContentPane().setLayout(new BorderLayout());
        
        JLabel titel = new JLabel("Order wijzigen", SwingConstants.CENTER);
        titel.setFont(WinkelApplication.computeFontSize(2));
        getContentPane().add(titel, BorderLayout.PAGE_START);
        
        getContentPane().add(createScrollPaneAndTable(), BorderLayout.CENTER);
        getContentPane().add(createEditBar(), BorderLayout.PAGE_END);
    }
    
    private JPanel createEditBar() {
        JPanel editBar = new JPanel();
        editBar.setLayout(new GridBagLayout());
        
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 0.5;
        
        JLabel lblProductId = new JLabel("Product ID");
        c.gridx = 0;
        c.gridy = 0;
        editBar.add(lblProductId, c);
        
        txtProductId = new JTextField();
        txtProductId.setEditable(false);
        c.gridx = 1;
        c.gridy = 0;
        editBar.add(txtProductId, c);
        
        JLabel lblNaam = new JLabel("Product");
        c.gridx = 0;
        c.gridy = 1;
        editBar.add(lblNaam, c);
        
        txtNaam = new JTextField();
        txtNaam.setEditable(false);
        c.gridx = 1;
        c.gridy = 1;
        editBar.add(txtNaam, c);        
        
        JLabel lblAantal = new JLabel("Aantal");
        c.gridx = 2;
        c.gridy = 0;
        editBar.add(lblAantal, c);
        
        txtAmount = new JTextField();
        c.gridx = 3;
        c.gridy = 0;
        editBar.add(txtAmount, c);
        
        JLabel lblPrice = new JLabel("Prijs");
        c.gridx = 2;
        c.gridy = 1;
        editBar.add(lblPrice, c);
        
        txtPrice = new JTextField();
        c.gridx = 3;
        c.gridy = 1;
        editBar.add(txtPrice, c);
        
        JButton saveBtn = new JButton("Opslaan");
        saveBtn.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {                
                if (txtProductId.getText().length() > 0)
                {
                    QueryManager queryManager = WinkelApplication
                                                    .getQueryManager();                    
                    
                    OrderRule orderRule = queryManager.getOrderRule(
                            orderId, Integer.parseInt(txtProductId.getText())
                        );

                    String newAmount = txtAmount.getText();
                    String newPrice = txtPrice.getText();                

                    try
                    {
                        int amount = Integer.parseInt(newAmount, 10);
                        double price = Double.parseDouble(newPrice);
                        
                        if (amount < 0)
                        {
                            JOptionPane.showMessageDialog(
                                    null, 
                                    "Het aantal moet groter zijn dan 0", 
                                    "Fout",
                                    JOptionPane.ERROR_MESSAGE
                                );                                               
                        }
                        else if (price < 0)
                        {
                            JOptionPane.showMessageDialog(
                                    null, 
                                    "U dient eerst een rij te selecteren", 
                                    "Fout",
                                    JOptionPane.ERROR_MESSAGE
                                );                   
                        }
                        else
                        {
                            orderRule.setAmount(amount);
                            orderRule.setPrice(price);

                            queryManager.updateOrderRule(orderRule);

                            model.setRowCount(0);
                            refreshOrderRules();                
                        }
                    }
                    catch (NumberFormatException ex)
                    {
                        JOptionPane.showMessageDialog(
                                null, 
                                "U heeft een verkeerde prijs en/of aantal ingevoerd", 
                                "Fout",
                                JOptionPane.ERROR_MESSAGE
                            );                                           
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(
                            null, 
                            "U dient eerst een rij te selecteren", 
                            "Fout",
                            JOptionPane.ERROR_MESSAGE
                        );                   
                }
            }
        });
        
        JButton cancelBtn = new JButton("Annuleren");
        cancelBtn.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent ae)
            {
                setVisible(false);
                dispose();
            }
        });
        
        Box btnBar = Box.createHorizontalBox();
        btnBar.add(saveBtn);
        btnBar.add(cancelBtn);
        
        c.gridx = 1;
        c.gridy = 4;
        
        editBar.add(btnBar);
        
        return editBar;
    }
    
    private JScrollPane createScrollPaneAndTable() {
        model.addColumn("#");
        model.addColumn("Product");
        model.addColumn("Aantal");
        model.addColumn("Prijs");
        
        refreshOrderRules();
        
        // Create the table
        orderRuleTable = new JTable(model) 
        {
            @Override
            public boolean isCellEditable(int row, int column) 
            {
                return false;
            }
        };
        
        orderRuleTable.addMouseListener(new MouseAdapter() 
        {

            @Override
            public void mouseClicked(MouseEvent e)
            {
                Vector modelData = model.getDataVector();
                Vector rowData = (Vector) modelData.get(orderRuleTable.getSelectedRow());
                
                // 0 = productId
                // 1 = productName
                // 2 = amount of products
                // 3 = price of the rule
                
                txtProductId.setText(rowData.get(0).toString());
                txtNaam.setText(rowData.get(1).toString());
                txtAmount.setText(rowData.get(2).toString());
                txtPrice.setText(rowData.get(3).toString());
            }
        });
        
        return new JScrollPane(orderRuleTable);
    }

    private void refreshOrderRules()
    {
        // Get all orders
        List<OrderRule> orderRules = WinkelApplication.getQueryManager().getOrderRules(orderId);
        
        for(OrderRule or : orderRules) 
        {
            Product p = or.getProduct();
            
            model.addRow(new Object[] { 
                p.getProductId(), 
                p.getName(),
                or.getAmount(),
                or.getPrice()
            });
        }
    }
}
